use crate::Syntax::expr::VariableExpression;
use crate::Syntax::syntaxResult::SyntaxResult;

use super::expr::{
    self, AssignmentExpression, CallExpression, GroupingExpression, LiteralExpression,
    LogicalExpression, UnaryExpression,
};
use super::lexical::LexicalScanner;
use super::object::Object;
use super::statements::{
    self, BlockStmt, BreakStmt, ExpressionStmt, FunctionStmts, IfStmts, PrinterStmt, ReturnStmt,
    Stmt, VariableDeclarationStmt, WhileStmts,
};
use super::token::{self, KeywordType};
use super::{
    expr::{BinaryExpression, SyntaxExpression},
    text::TextSpan,
    token::{SyntaxKind, SyntaxToken},
};
use std::fmt::{Arguments, LowerExp};
use std::panic::Location;
use std::rc::Rc;
use std::{error, vec};
use std::{marker::PhantomData, vec::Vec};

#[allow(non_snake_case)]
pub struct SyntaxParser {
    inputTokens: Vec<SyntaxToken>,
    current: usize,
    hasError: bool,
}

#[allow(non_snake_case)]
impl<'a> SyntaxParser {
    pub fn new() -> Self {
        Self {
            inputTokens: Vec::new(),
            current: 0,
            hasError: false,
        }
    }
    pub fn fromInputCode(inputCode: &'a str) -> Self {
        let mut lexer = LexicalScanner::new(inputCode);
        let mut tokens = Vec::new();

        while let Some(token) = lexer.nextToken() {
            let kind = token.kind.clone();
            //跳过空白符，注释;
            if !matches!(kind, SyntaxKind::Whitespace | SyntaxKind::Comments) {
                tokens.push(token);

                if kind.eq(&SyntaxKind::Eof) {
                    break;
                }
            }
        }
        Self {
            inputTokens: tokens,
            current: 0,
            hasError: false,
        }
    }

    fn peek(&mut self, offset: usize, accumulate: bool) -> Option<&SyntaxToken> {
        let index = self.current + offset;

        if index >= self.inputTokens.len() {
            return self.inputTokens.last();
        }

        self.current += accumulate as usize;

        return self.inputTokens.get(index);
    }

    pub fn currentToken(&mut self) -> &SyntaxToken {
        self.peek(0, false).unwrap()
    }

    pub fn nextToken(&mut self) -> &SyntaxToken {
        self.peek(0, true).unwrap()
    }

    fn check(&mut self, tokenKind: SyntaxKind) -> bool {
        return self.currentToken().kind == tokenKind;
    }
    fn checked(&mut self, tokenKind: SyntaxKind) -> bool {
        if self.currentToken().kind == tokenKind {
            self.advance();
            return true;
        }
        false
    }

    pub fn isSuccess(&self) -> bool {
        !self.hasError
    }

    fn error(&mut self, token: &SyntaxToken, msg: &str) -> SyntaxResult {
        self.hasError = true;
        SyntaxResult::ParserError(token, msg)
    }
    /// 不消耗令牌;
    fn isMatches(&mut self, types: &[SyntaxKind]) -> bool {
        let currentlyKind = &self.currentToken().kind;
        for tokenKind in types {
            if currentlyKind.eq(tokenKind) {
                return true;
            }
        }
        false
    }
    fn advance(&mut self) {
        self.current += 1;
    }
    // 关键字;
    fn isKeyWord(&mut self, key: &str) -> bool {
        if self.check(SyntaxKind::Identifier) && self.currentToken().as_string().eq(key) {
            return true;
        }
        false
    }

    fn consume(&mut self, kind: SyntaxKind, message: &str) -> Result<&SyntaxToken, SyntaxResult> {
        if (self.check(kind)) {
            return Ok(self.nextToken());
        }
        Err(SyntaxResult::ParserError(self.currentToken(), message))
    }

    pub fn parse(&mut self) -> Result<Vec<Stmt>, SyntaxResult> {
        let mut statements = Vec::new();

        while !self.isMatches(&[SyntaxKind::Eof]) {
            statements.push(self.declaration()?)
        }
        Ok(statements)
    }

    pub fn statements(&mut self) -> Result<Stmt, SyntaxResult> {
        if self.checked(SyntaxKind::If) {
            return self.ifStatement();
        }
        if self.checked(SyntaxKind::For) {
            return self.ForStatement();
        }
        if self.checked(SyntaxKind::While) {
            return self.WhileStatement();
        }
        if self.check(SyntaxKind::Break) {
            return self.BreakStatement();
        }
        if self.check(SyntaxKind::Return) {
            return self.ReturnStatement();
        }
        if self.isKeyWord("print") {
            self.advance();
            return self.printStatement();
        }
        if self.checked(SyntaxKind::OpenBrace) {
            return Ok(Stmt::Block(BlockStmt {
                statements: self.blockStatement()?,
            }));
        }

        self.expressionStatement()
    }
    fn ForStatement(&mut self) -> Result<Stmt, SyntaxResult> {
        self.consume(SyntaxKind::OpenParenthesis, "Expect '(' after 'for' .")?;

        //initializer;
        let initializer = if self.check(SyntaxKind::Semicolon) {
            None
        } else if self.checked(SyntaxKind::Var) {
            Some(self.varDeclaration()?)
        } else {
            Some(self.expressionStatement()?)
        };

        // condition;
        let condition = if self.check(SyntaxKind::Semicolon) {
            None
        } else {
            Some(self.expression()?)
        };

        self.consume(SyntaxKind::Semicolon, "Expect ';' after loop condition .")?;
        // increment;
        let increment = if self.check(SyntaxKind::CloseParenthesis) {
            None
        } else {
            Some(self.expression()?)
        };
        self.consume(
            SyntaxKind::CloseParenthesis,
            "Expect ')' after for clauses .",
        )?;

        // body;
        //let mut body = self.statements()?;//Error cannot be displayed when '{' is missing

        self.consume(SyntaxKind::OpenBrace, "Expect '{' after 'for' body .")?;
        let mut body = Stmt::Block(BlockStmt {
            statements: self.blockStatement()?,
        });
        
        //make body -> add increment ;
        if let Some(_increment) = increment {
            body = Stmt::Block(BlockStmt {
                statements: vec![
                    body,
                    Stmt::Expression(ExpressionStmt {
                        expression: _increment,
                    }),
                ],
            });
        }

        //make body -> add condition ;
        body = Stmt::While(WhileStmts {
            condition: if let Some(_condition) = condition {
                _condition
            } else {
                SyntaxExpression::Literal(LiteralExpression {
                    value: Some(Object::Bool(true)),
                })
            },
            body: Box::new(body),
        });

        if let Some(init) = initializer {
            body = Stmt::Block(BlockStmt {
                statements: vec![init, body],
            });
        }

        Ok(body)
    }
    fn WhileStatement(&mut self) -> Result<Stmt, SyntaxResult> {
        self.consume(SyntaxKind::OpenParenthesis, "Expect '(' after 'while' .")?;
        let _condition = self.expression()?;
        self.consume(SyntaxKind::CloseParenthesis, "Expect ')' after 'while' .")?;

        //
        self.consume(SyntaxKind::OpenBrace, "Expect '{' after 'while' body .")?;
        let mut body = Stmt::Block(BlockStmt {
            statements: self.blockStatement()?,
        });

        // Ok(Stmt::While(WhileStmts {
        //     condition: _condition,
        //     body: Box::new(self.statements()?),
        // }))
        Ok(Stmt::While(WhileStmts {
            condition: _condition,
            body: Box::new(body),
        }))
    }
    fn ifStatement(&mut self) -> Result<Stmt, SyntaxResult> {
        self.consume(SyntaxKind::OpenParenthesis, "Expect '(' after 'if' .")?;
        let _condition = self.expression()?;
        self.consume(SyntaxKind::CloseParenthesis, "Expect ')' after 'if' .")?;

        let than_branch = Box::new(self.statements()?);
        let else_branch = if self.checked(SyntaxKind::Else) {
            Some(Box::new(self.statements()?))
        } else {
            None
        };
        Ok(Stmt::If(IfStmts {
            condition: _condition,
            thenBranch: than_branch,
            elseBranch: else_branch,
        }))
    }
    fn blockStatement(&mut self) -> Result<Vec<Stmt>, SyntaxResult> {
        let mut statements = Vec::new();

        while !self.isMatches(&[SyntaxKind::CloseBrace, SyntaxKind::Eof]) {
            statements.push(self.declaration()?);
        }
        self.consume(SyntaxKind::CloseBrace, "Expect '}' after block.")?;

        Ok(statements)
    }
    fn printStatement(&mut self) -> Result<Stmt, SyntaxResult> {
        let mut expr = self.expression()?;

        
        self.consume(SyntaxKind::Semicolon, "Expect ';' after print value.")?;

        Ok(Stmt::Printer(PrinterStmt { expression: expr }))
    }
    fn BreakStatement(&mut self) -> Result<Stmt, SyntaxResult> {
        let tk = self.nextToken().clone();
        self.consume(SyntaxKind::Semicolon, "Expect ';' after 'break' statement .")?;

        Ok(Stmt::Break(BreakStmt { token: tk }))
    }
    // 声明;
    fn declaration(&mut self) -> Result<Stmt, SyntaxResult> {
        let result = if self.checked(SyntaxKind::Var) {
            // e.g: var aa = 155;
            //self.advance();
            self.varDeclaration()
        } else if self.checked(SyntaxKind::Func) {
            self.FunctionDeclaration("function")
        } else {
            self.statements()
        };
        // if result.is_err(){
        // }

        result
    }

    fn ReturnStatement(&mut self) -> Result<Stmt, SyntaxResult> {
        let _keyword = self.nextToken().clone();

        let expr = if self.check(SyntaxKind::Semicolon) {
            None
        } else {
            Some(self.expression()?)
        };
        self.consume(SyntaxKind::Semicolon, "Expect ';' after return value.")?;

        Ok(Stmt::Return(ReturnStmt {
            keyword: _keyword,
            value: expr,
        }))
    }
    // 函数
    fn FunctionDeclaration(&mut self, kind: &str) -> Result<Stmt, SyntaxResult> {
        let _name = self
            .consume(SyntaxKind::Identifier, &format!("Expect {kind} name."))?
            .clone();

        self.consume(
            SyntaxKind::OpenParenthesis,
            &format!("Expect '(' after {kind} name."),
        )?;
        let mut _parameters = Vec::new();
        if !self.check(SyntaxKind::CloseParenthesis) {
            loop {
                if _parameters.len() >= 255 {
                    return Err(SyntaxResult::ParserError(
                        &self.currentToken().clone(),
                        "Can't have more than 255 parameter.",
                    ));
                }
                _parameters.push(
                    self.consume(SyntaxKind::Identifier, "Expect parameter name.")?
                        .clone(),
                );

                if !self.checked(SyntaxKind::Comma) {
                    break;
                }
            }
        }

        self.consume(SyntaxKind::CloseParenthesis, "Expect ')' after parameter .")?;

        self.consume(
            SyntaxKind::OpenBrace,
            &format!("Expect '{{' after {kind} body."),
        )?;

        let _body = Rc::new(self.blockStatement()?);

        Ok(Stmt::Function(FunctionStmts {
            name: _name,
            params: Rc::new(_parameters),
            body: _body,
        }))
    }
    // 变量声明;
    fn varDeclaration(&mut self) -> Result<Stmt, SyntaxResult> {
        if !self.check(SyntaxKind::Identifier) {
            return Err(SyntaxResult::ParserError(
                self.currentToken(),
                " Expect variable name.",
            ));
        }

        let varToken_name = self.nextToken().clone();

        let var_initializer = if self.checked(SyntaxKind::Assignment) {
            //self.advance();
            Some(self.expression()?)
        } else {
            None
        };
        self.consume(
            SyntaxKind::Semicolon,
            "Expect:';' after variable declaration.",
        )?;

        Ok(Stmt::VariableDeclaration(VariableDeclarationStmt {
            name: varToken_name,
            initializer: var_initializer,
        }))
    }

    fn expressionStatement(&mut self) -> Result<Stmt, SyntaxResult> {
        let mut expr = self.expression()?;

        self.consume(SyntaxKind::Semicolon, "Expect ';' after value.")?;
        Ok(Stmt::Expression(ExpressionStmt { expression: expr }))
    }

    pub fn expression(&mut self) -> Result<SyntaxExpression, SyntaxResult> {
        //let mut expr = self.equality()?;
        // while self.isMatches(&[SyntaxKind::Comma]) {
        //     self.advance();
        //     expr = self.equality()?;
        // }
        //Ok(expr)
        self.assignment()
    }
    //赋值;
    fn assignment(&mut self) -> Result<SyntaxExpression, SyntaxResult> {
        let expr = self.logicalOr()?;

        if self.check(SyntaxKind::Assignment) {
            let equals = self.nextToken().clone();
            let value = self.assignment()?;

            // 先判断是否是变量表达 ;
            if let SyntaxExpression::Variable(expr) = expr {
                return Ok(SyntaxExpression::Assignment(AssignmentExpression {
                    name: expr.name,
                    value: Box::new(value),
                }));
            }

            self.error(&equals, "Invalid assignment target.");
        }
        Ok(expr)
    }

    fn logicalOr(&mut self) -> Result<SyntaxExpression, SyntaxResult> {
        let mut expr = self.logicalAnd()?;
        while self.check(SyntaxKind::Or) {
            // 不要修改下面的顺序,否则会错误;
            expr = SyntaxExpression::Logical(LogicalExpression {
                operator: self.nextToken().clone(),
                left: Box::new(expr),
                right: Box::new(self.logicalAnd()?),
            });
        }
        Ok(expr)
    }
    fn logicalAnd(&mut self) -> Result<SyntaxExpression, SyntaxResult> {
        let mut expr = self.equality()?;
        while self.check(SyntaxKind::And) {
            // 不要修改下面的顺序,否则会错误;
            expr = SyntaxExpression::Logical(LogicalExpression {
                operator: self.nextToken().clone(),
                left: Box::new(expr),
                right: Box::new(self.equality()?),
            });
        }
        Ok(expr)
    }
    // 等式;
    fn equality(&mut self) -> Result<SyntaxExpression, SyntaxResult> {
        let mut expr = self.comparison()?;

        while self.isMatches(&[SyntaxKind::BangEquals, SyntaxKind::Equals]) {
            expr = SyntaxExpression::Binary(BinaryExpression {
                left: Box::new(expr),
                operator: self.nextToken().clone(),
                right: Box::new(self.comparison()?),
            });
        }
        Ok(expr)
    }

    // 比较;
    fn comparison(&mut self) -> Result<SyntaxExpression, SyntaxResult> {
        let mut expr = self.Terms()?;

        while self.isMatches(&[
            SyntaxKind::Less,
            SyntaxKind::LessEquals,
            SyntaxKind::Greater,
            SyntaxKind::GreaterEquals,
        ]) {
            expr = SyntaxExpression::Binary(BinaryExpression {
                left: Box::new(expr),
                operator: self.nextToken().clone(),
                right: Box::new(self.Terms()?),
            });
        }

        Ok(expr)
    }
    fn Terms(&mut self) -> Result<SyntaxExpression, SyntaxResult> {
        let mut expr = self.factor()?;

        while self.isMatches(&[SyntaxKind::Minus, SyntaxKind::Plus]) {
            expr = SyntaxExpression::Binary(BinaryExpression {
                left: Box::new(expr),
                operator: self.nextToken().clone(),
                right: Box::new(self.factor()?),
            });
        }
        Ok(expr)
    }
    // 乘/除/余;
    fn factor(&mut self) -> Result<SyntaxExpression, SyntaxResult> {
        let mut expr = self.Unary()?;

        while self.isMatches(&[SyntaxKind::Slash, SyntaxKind::Asterisk, SyntaxKind::Percent]) {
            expr = SyntaxExpression::Binary(BinaryExpression {
                left: Box::new(expr),
                operator: self.nextToken().clone(),
                right: Box::new(self.Unary()?),
            });
        }
        Ok(expr)
    }

    //一元表达式;
    fn Unary(&mut self) -> Result<SyntaxExpression, SyntaxResult> {
        if self.isMatches(&[SyntaxKind::Bang, SyntaxKind::Minus]) {
            return Ok(SyntaxExpression::Unary(UnaryExpression {
                operator: self.nextToken().clone(),
                right: Box::new(self.Unary()?),
            }));
        }
        self.Call()
    }
    // 函数调用;
    fn Call(&mut self) -> Result<SyntaxExpression, SyntaxResult> {
        let mut expr = self.primary()?;
        loop {
            if self.checked(SyntaxKind::OpenParenthesis) {
                //self.advance();
                expr = self.finishCall(&Rc::new(expr))?;
            } else {
                break;
            }
        }
        Ok(expr)
    }
    fn finishCall(
        &mut self,
        _callee: &Rc<SyntaxExpression>,
    ) -> Result<SyntaxExpression, SyntaxResult> {
        let mut _arguments = Vec::new();

        if !self.check(SyntaxKind::CloseParenthesis) {
            loop {
                if _arguments.len() >= 255 {
                    return Err(SyntaxResult::ParserError(
                        self.currentToken(),
                        "Can't have more than 255 arguments.",
                    ));
                }
                _arguments.push(self.expression()?);
                if !self.checked(SyntaxKind::Comma) {
                    break;
                }
                //self.advance();
            }
        }
        let _paren = self.consume(SyntaxKind::CloseParenthesis, "Expect ')' after arguments.")?;

        Ok(SyntaxExpression::Call(CallExpression {
            callee: Rc::clone(_callee),
            paren: _paren.clone(),
            arguments: _arguments,
        }))
    }
    //初级;
    fn primary(&mut self) -> Result<SyntaxExpression, SyntaxResult> {
        if self.isKeyWord("false") {
            self.advance();
            return Ok(SyntaxExpression::Literal(LiteralExpression {
                value: Some(Object::Bool(false)),
            }));
        }
        if self.isKeyWord("true") {
            self.advance();
            return Ok(SyntaxExpression::Literal(LiteralExpression {
                value: Some(Object::Bool(true)),
            }));
        }
        if self.isKeyWord("nil") {
            self.advance();
            return Ok(SyntaxExpression::Literal(LiteralExpression {
                value: Some(Object::Nil),
            }));
        }
        if self.check(SyntaxKind::Number) {
            let str = self.nextToken().as_string();

            return Ok(SyntaxExpression::Literal(LiteralExpression {
                value: Some(Object::Number(str.parse().unwrap())),
            }));
        }

        if self.check(SyntaxKind::String) {
            let str = self.nextToken().as_string();

            return Ok(SyntaxExpression::Literal(LiteralExpression {
                value: Some(Object::String(str.parse().unwrap())),
            }));
        }
        if self.check(SyntaxKind::Identifier) {
            return Ok(SyntaxExpression::Variable(VariableExpression {
                name: self.nextToken().clone(),
            }));
        }

        if self.checked(SyntaxKind::OpenParenthesis) {
            let expr = SyntaxExpression::Grouping(GroupingExpression {
                expression: Box::new(self.expression()?),
            });

            if !self.check(SyntaxKind::CloseParenthesis) {
                return Err(SyntaxResult::ParserError(
                    self.currentToken(),
                    "Expect ')' after expression",
                ));
            }
            self.advance();
            //self.consume(SyntaxKind::CloseParenthesis, "Expect ')' after expression");
            return Ok(expr);
        }

        //panic!("Expect expression");
        Err(SyntaxResult::ParserError(
            self.currentToken(),
            "Expect expression.",
        ))
    }
}
